from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, send_from_directory
from datetime import datetime
import os
from PIL import Image
from pdf2image import convert_from_path
import shutil
from database import ContractDatabase

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'  # 请更改为安全的密钥
app.config['UPLOAD_FOLDER'] = os.path.join('static', 'uploads', 'contracts')
app.config['DELETED_FOLDER'] = os.path.join('static', 'uploads', 'contracts_deleted')

# 确保所有必要的目录都存在
def ensure_directories():
    directories = [
        'static',
        os.path.join('static', 'uploads'),
        app.config['UPLOAD_FOLDER'],
        app.config['DELETED_FOLDER'],
        os.path.join('static', 'js'),
        os.path.join('static', 'css'),
        'templates'
    ]
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

# 创建必要的目录
ensure_directories()

db = ContractDatabase()

# 模拟当前登录用户
CURRENT_USER = {
    'username': 'admin',
    'role': 'admin'  # 可以是 'admin' 或 'user'
}

def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf', 'jpg', 'jpeg', 'png'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def convert_to_images(file_path, output_dir):
    """将PDF文档转换为图片"""
    try:
        file_ext = file_path.rsplit('.', 1)[1].lower()
        if file_ext == 'pdf':
            images = convert_from_path(file_path)
            image_paths = []
            for i, image in enumerate(images):
                image_path = os.path.join(output_dir, f'page_{i+1}.jpg')
                image.save(image_path, 'JPEG')
                image_paths.append(image_path)
            return image_paths
        return []
    except Exception as e:
        print(f"转换文件时出错: {str(e)}")
        return []

@app.route('/')
def index():
    # 获取筛选参数
    date_from = request.args.get('date_from')
    date_to = request.args.get('date_to')
    company = request.args.get('company')
    cate = request.args.get('cate')
    item_type = request.args.get('item_type')

    # 根据筛选条件获取合同列表
    if date_from and date_to:
        contracts = db.get_contracts_by_date_range(date_from, date_to)
    elif company:
        contracts = db.get_contracts_by_company(company)
    elif cate:
        contracts = db.get_contracts_by_type(cate)
    elif item_type:
        contracts = db.get_contracts_by_item(item_type)
    else:
        contracts = db.get_all_contracts()

    return render_template('index.html', 
                         contracts=contracts,
                         current_user=CURRENT_USER)

@app.route('/contract/new', methods=['GET', 'POST'])
def new_contract():
    if request.method == 'POST':
        try:
            # 生成唯一编号
            current_date = datetime.now()
            unique_id = f"CONTRACT-{current_date.strftime('%Y%m%d')}-{current_date.strftime('%H%M%S')}"

            # 收集表单数据
            contract_data = (
                request.form['pro_name'],      # 项目名称
                request.form['my_comma'],      # 我方公司
                request.form['ven_name'],      # 供应商名称
                unique_id,                     # 唯一编号
                request.form['item_sup'],      # 供应物品
                request.form['people'],        # 负责人
                float(request.form['money']),  # 金额
                request.form['date'],          # 日期
                request.form['cate'],          # 类别（对公/对私）
                '待审批',                      # 初始状态
                request.form.get('note', '')   # 备注
            )

            # 创建合同记录
            db.create_contract(contract_data)

            # 处理文件上传
            if 'files' in request.files:
                files = request.files.getlist('files')
                for file in files:
                    if file and allowed_file(file.filename):
                        filename = f"{unique_id}_{file.filename}"
                        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                        # 确保目录存在
                        os.makedirs(os.path.dirname(file_path), exist_ok=True)
                        file.save(file_path)

                        # 如果是 PDF 文件，转换为图片
                        if file.filename.lower().endswith('.pdf'):
                            output_dir = os.path.join(app.config['UPLOAD_FOLDER'], f'converted_{unique_id}')
                            os.makedirs(output_dir, exist_ok=True)
                            convert_to_images(file_path, output_dir)

            flash('合同创建成功！', 'success')
            return redirect(url_for('index'))
        except Exception as e:
            flash(f'创建合同时出错：{str(e)}', 'error')
            return redirect(url_for('new_contract'))

    return render_template('new_contract.html', current_user=CURRENT_USER)

@app.route('/contract/<int:id>')
def view_contract(id):
    try:
        contract = db.get_contract(id)
        if not contract:
            flash('合同不存在！', 'error')
            return redirect(url_for('index'))

        # 获取合同相关的文件
        contract_files = []
        contract_dir = app.config['UPLOAD_FOLDER']
        if os.path.exists(contract_dir):
            for file in os.listdir(contract_dir):
                if file.startswith(contract['unique_id']):
                    contract_files.append(file)

        # 获取转换后的图片
        converted_images = []
        converted_dir = os.path.join(app.config['UPLOAD_FOLDER'], f'converted_{contract["unique_id"]}')
        if os.path.exists(converted_dir):
            converted_images = [f for f in os.listdir(converted_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]

        return render_template('view_contract.html',
                            contract=contract,
                            files=contract_files,
                            images=converted_images,
                            current_user=CURRENT_USER)
    except Exception as e:
        flash(f'查看合同时出错：{str(e)}', 'error')
        return redirect(url_for('index'))

@app.route('/contract/<int:id>/approve', methods=['POST'])
def approve_contract(id):
    if CURRENT_USER['role'] != 'admin':
        flash('您没有权限审批合同！', 'error')
        return redirect(url_for('view_contract', id=id))

    status = request.form['status']
    comment = request.form.get('comment', '')

    # 更新合同状态
    db.update_contract_status(id, status)

    # 记录审批信息
    approval_data = (id, CURRENT_USER['username'], status, comment)
    db.create_approval_record(approval_data)

    flash('审批操作已完成！', 'success')
    return redirect(url_for('view_contract', id=id))

@app.route('/contract/<int:id>/delete', methods=['POST'])
def delete_contract(id):
    try:
        contract = db.get_contract(id)
        if not contract:
            flash('合同不存在！', 'error')
            return redirect(url_for('index'))

        # 移动文件到删除目录
        contract_dir = app.config['UPLOAD_FOLDER']
        if os.path.exists(contract_dir):
            for file in os.listdir(contract_dir):
                if file.startswith(contract['unique_id']):
                    old_path = os.path.join(contract_dir, file)
                    new_path = os.path.join(app.config['DELETED_FOLDER'], file)
                    # 确保目标目录存在
                    os.makedirs(os.path.dirname(new_path), exist_ok=True)
                    shutil.move(old_path, new_path)

            # 移动转换后的图片目录
            converted_dir = os.path.join(contract_dir, f'converted_{contract["unique_id"]}')
            if os.path.exists(converted_dir):
                new_converted_dir = os.path.join(app.config['DELETED_FOLDER'], f'converted_{contract["unique_id"]}')
                shutil.move(converted_dir, new_converted_dir)

        # 更新合同状态为已删除
        db.update_contract_status(id, 'deleted')

        flash('合同已移至回收站！', 'success')
        return redirect(url_for('index'))
    except Exception as e:
        flash(f'删除合同时出错：{str(e)}', 'error')
        return redirect(url_for('index'))

@app.route('/uploads/<path:filename>')
def download_file(filename):
    """下载或查看文件"""
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True) 